package com.dh.spring.thread.callable;

import com.dh.spring.thread.CustomDefaultThreadFactory;
import com.dh.spring.thread.CustomDefaultThreadPool;
import com.dh.spring.thread.CustomTaskBlockQueue;
import com.dh.spring.thread.CustomThreadPool;
import com.dh.spring.thread.runnable.InternalRunnableTask;
import com.dh.spring.util.LocalTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class InternalCallableTask implements Callable {
    private static final Logger logger = LoggerFactory.getLogger(InternalCallableTask.class);
    private CustomTaskBlockQueue customTaskBlockQueue;
    private CustomThreadPool customThreadPool;
    //TODO 线程执行单元运行状态 true停止 false运行
    private volatile boolean isStop = false;

    public InternalCallableTask(CustomThreadPool customThreadPool, CustomTaskBlockQueue customTaskBlockQueue) {
        this.customThreadPool = customThreadPool;
        this.customTaskBlockQueue = customTaskBlockQueue;
    }

    @Override
    public Object call() throws Exception {
        FutureTask<Callable> futureTask = null;
        try {
            //TODO　循环从队列获取任务，如果能获取到则执行自定义任务处理，否则进行阻塞
            while(!isStop) {
                futureTask = this.customTaskBlockQueue.takeCallable();
                if(null != futureTask) {
                    //TODO 执行上传文件的逻辑
                    futureTask.run();

                    //TODO 一旦执行完成返回，线程池活跃线程数减1，并移除对应任务;
                    CustomDefaultThreadFactory.releaseThread(this.customThreadPool);
                    ((CustomDefaultThreadPool) this.customThreadPool).getList().remove(this);
                    return futureTask;
                }
            }
        } catch (Exception e) {
            logger.info("[ " + LocalTime.formatDate(LocalDateTime.now()) + " ]"
                + " 当前线程 thread = " + Thread.currentThread().getName() + "中断，异常为：" + e.getMessage());
            e.printStackTrace();
        }

        return futureTask;
    }

    //TODO 线程执行单元停滞任务执行
    public void stop() {
        this.isStop = true;
    }

}
